#ifndef SMTPMAILER_H
#define SMTPMAILER_H

#include <QObject>
#include <QTcpSocket>
#include <QSslSocket>
#include <QString>
#include <QByteArray>
#include <QTimer>

class SmtpMailer : public QObject
{
    Q_OBJECT

public:
    explicit SmtpMailer(QObject *parent = nullptr);
    
    void setServerConfig(const QString &host, int port, bool useSSL = true);
    void setCredentials(const QString &username, const QString &password);
    void sendMail(const QString &to, const QString &subject, const QString &body);

signals:
    void mailSent();
    void mailError(const QString &error);

private slots:
    void onConnected();
    void onReadyRead();
    void onError(QAbstractSocket::SocketError error);
    void onSslErrors(const QList<QSslError> &errors);
    void onEncrypted();
    void onTimeout();

private:
    void sendCommand(const QString &command);
    void processResponse();
    void nextStep();
    QString encodeBase64(const QString &text);
    
    QSslSocket *m_socket;
    QTimer *m_timer;
    
    QString m_host;
    int m_port;
    bool m_useSSL;
    QString m_username;
    QString m_password;
    
    QString m_to;
    QString m_subject;
    QString m_body;
    
    enum State {
        Init,
        Connected,
        EhloSent,
        StartTlsSent,
        AuthLoginSent,
        UsernameSent,
        PasswordSent,
        MailFromSent,
        RcptToSent,
        DataSent,
        BodySent,
        Finished,
        Error
    };
    
    State m_state;
    QString m_response;
};

#endif // SMTPMAILER_H